package cn.oldfeel.spark.fragment;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import cn.oldfeel.spark.R;
import cn.oldfeel.spark.base.BaseFragment;
import cn.oldfeel.spark.ui.Main;
import cn.oldfeel.spark.util.XMPPHelper;

/**
 * 好友列表
 * 
 * @author oldfeel
 * 
 */
@SuppressLint("HandlerLeak")
public class FriendList extends BaseFragment implements OnItemClickListener {
	ListView listView;
	ArrayAdapter<String> adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.friend_list, null);
		listView = (ListView) view.findViewById(R.id.friend_list);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		XMPPHelper.getInstance().getFriendList(handler);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			@SuppressWarnings("unchecked")
			ArrayList<String> friendList = (ArrayList<String>) msg.obj;
			adapter = getFriendListAdapter(friendList);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(FriendList.this);
		};
	};

	/**
	 * 获取好友 列表适配器
	 * 
	 * @param friendList
	 * @return
	 */
	protected ArrayAdapter<String> getFriendListAdapter(
			ArrayList<String> friendList) {
		return new ArrayAdapter<String>(getActivity(),
				R.layout.friend_item, R.id.friend_item_name,
				friendList);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		String name = adapter.getItem(position);
		((Main) getActivity()).startChat(name);
	}
}
